package cn.net.zj.scan.api;

import com.google.zxing.common.StringUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import cn.net.zj.scan.FKApplication;
import cn.net.zj.scan.utils.SharedPreferencesUtils;
import cn.net.zj.scan.utils.ZjConfig;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Huan on 2018/2/26.
 */

public class HttpMethods {


    private Retrofit retrofit;
    private FYApi FYApi;


    public static HttpMethods getInstance(){
        HttpMethods instance = new HttpMethods();
        return instance;
    }

    /**\
     * @return FYApi
     */
    public FYApi getFyApi(){
        //声明日志类
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        //设定日志级别
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15,TimeUnit.SECONDS) //设置请求超时
                .readTimeout(15,TimeUnit.SECONDS)
                .writeTimeout(15,TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        String userName = (String) SharedPreferencesUtils.getParam(FKApplication.getContext(),ZjConfig.userName,"");
                        userName = URLEncoder.encode(userName);
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .header("userName", userName+"");
                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ZjConfig.baseUrl) // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava
                .client(client)
                .build();

        FYApi = retrofit.create(FYApi.class);

        return FYApi;

    }








}
